/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.sys.web.user;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.BeanChangeUtil;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGenerate;
import com.jeesite.common.io.ResourceUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.mybatis.mapper.query.QueryWhere;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.annotation.ExcelField.Type;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.EduTwoOrganizationValues;
import com.jeesite.modules.edu.entity.EduTwoOrganization;
import com.jeesite.modules.edu.service.EduTwoOrganizationService;
import com.jeesite.modules.sys.entity.Company;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.EmployeePost;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.Post;
import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.entity.UserDataScope;
import com.jeesite.modules.sys.service.CompanyService;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.PostService;
import com.jeesite.modules.sys.service.RoleService;
import com.jeesite.modules.sys.service.SystemService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.total.UserState;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;

import jline.internal.Log;

/**
 * 员工用户Controller
 * @author ThinkGem
 * @version 2017-03-26
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/empUser")
@ConditionalOnProperty(name="web.core.enabled", havingValue="true", matchIfMissing=true)
public class EmpUserController extends BaseController {

	@Autowired
	private EmpUserService empUserService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private PostService postService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EduTwoOrganizationService eduTwoOrganizationService;
	@ModelAttribute
	public EmpUser get(String userCode, boolean isNewRecord) {
		return empUserService.get(userCode, isNewRecord);
	}

	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "index")
	public String index(EmpUser empUser, Model model) {
		return "modules/sys/user/empUserIndex";
	}
	//获取通讯录
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "address")
	public String address(EmpUser empUser, Model model) {
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		return "modules/sys/user/empAddressList";
	}
	
	@RequestMapping(value = "addressData")
	@ResponseBody
	public Page<EmpUser> addressData(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletRequest request, HttpServletResponse response) {
		User user = UserUtils.getUser();
		String officeCode = null;
		if (!user.isAdmin()) {
			Employee employee = employeeService.get(user.getRefCode());
			if(!org.springframework.util.StringUtils.isEmpty(employee)) {
				Office office = employee.getOffice();
				if(!org.springframework.util.StringUtils.isEmpty(office)) {
					officeCode = office.getOfficeCode();
				}
				
			}
		}
		
		if(user.isAdmin()) {
			String loginAdmin = user.getLoginCode();
			logger.info("进行数据更新...判断是否是管理员....{}",loginAdmin);
			if(!org.springframework.util.StringUtils.isEmpty(loginAdmin)) {
				if (loginAdmin.indexOf("MANAGER")>-1) {
						Employee employee = empUser.getEmployee();
						String createBy = loginAdmin.substring(0,loginAdmin.indexOf("_MANAGER"));
						String[] values = null;
						if(!org.springframework.util.StringUtils.isEmpty(EduTwoOrganizationValues.map.get(loginAdmin))) {
							EduTwoOrganization eduTwoOrganization = new EduTwoOrganization();
							eduTwoOrganization.getSqlMap().getWhere()
							.andBracket("create_by", QueryType.EQ, createBy,2).or("create_by", QueryType.EQ, "system",3).endBracket()
							.and("dict_label", QueryType.EQ, EduTwoOrganizationValues.map.get(loginAdmin));
							List<EduTwoOrganization> eduTwoOrganizations = eduTwoOrganizationService.findList(eduTwoOrganization);
							
							List<String> ll = new ArrayList<String>();
							for(EduTwoOrganization eo: eduTwoOrganizations) {
								ll.add(eo.getDictCode());
							}
							values = ll.toArray(new String[ll.size()]);
							if(CollectionUtils.isEmpty(ll)||ll.size()==0) {
								values = new String[] {"1"};
							}
							
							logger.info("AND->OR...START");
							QueryWhere QueryWhere = employee.getSqlMap().getWhere().and("two_organization_code",  QueryType.IN, values);
							logger.info("AND->OR...END--->" + QueryWhere.toSql());
							
							empUser.setEmployee(employee);
						}
						
						employee.setCreateBy(createBy);
						logger.info("是否进入变更状态...");
				}
				
				if (loginAdmin.indexOf("SUPER")>-1) {
					Employee ee = employeeService.get(user.getUserCode());
					String users = ee.getRemarks();
					if (!org.springframework.util.StringUtils.isEmpty(users) && users.indexOf("_ADMIN") > -1) {
						String[] codes = users.split(",");
						empUser.getSqlMap().getWhere().and("create_by", QueryType.IN, codes); 
					}
				}
			}
		}
		
		empUser.getEmployee().getOffice().setOfficeCode(officeCode);
		empUser.setPage(new Page<>(request, response));
		Page<EmpUser> page = empUserService.findPage(empUser);
		return page;
	}
	
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "action")
	public String action(Employee employee, Model model) {
		model.addAttribute("action", employee.getAction());
		String officeCode = "";
		if(!org.springframework.util.StringUtils.isEmpty(employee.getOffice())) {
			officeCode = employee.getOffice().getOfficeCode();
		}
		model.addAttribute("officeCode", officeCode);
		return "modules/sys/user/empUserAction";
	}
	
	
	@RequiresPermissions("user")
	@RequestMapping(value = "actionData")
	@ResponseBody
	public Page<EmpUser> actionData(Employee employee, Boolean isAll, String ctrlPermi, HttpServletRequest request, HttpServletResponse response) {
		employee.setPage(new Page<>(request, response));
		Page<Employee> page = (Page<Employee>) employee.getPage();
		List<Employee> employees = employeeService.findListByAction(employee);
		List list = new ArrayList();
		for(Employee e : employees) {
			EmpUser emp = empUserService.get(e.getEmpCode());
			list.add(emp);
		}
		Page<EmpUser> pp = new Page<EmpUser>();
		pp.setCount(page.getCount());
		pp.setPageSize(page.getPageSize());
		pp.setPageNo(page.getPageNo());
		pp.setList(list);
		return pp;
	}
	
	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportAction")
	public void exportAction(Employee employee, Boolean isAll, String ctrlPermi, HttpServletResponse response) {

		List<Employee> list = employeeService.findListByAction(employee);
		List<UserDto> eus = new ArrayList<UserDto>();
		for(Employee e : list) {
			EmpUser ss = empUserService.get(e.getEmpCode());
			if(org.springframework.util.StringUtils.isEmpty(ss)) {
				logger.info("当前异常数据信息:{}",e.getEmpCode());
				continue;
			}
			UserDto UserDto = new UserDto();
			UserDto.setMobile(ss.getMobile());
			UserDto.setUsername(ss.getUserName());
			Office office = e.getOffice();
			if(office!=null) {
				UserDto.setOfficeName(office.getOfficeName());
			}
			UserDto.setOrganization(e.getOrganization());
			eus.add(UserDto);
		}
		String fileName = "教师数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("教师数据", UserDto.class)){
			ee.setDataList(eus).write(response, fileName);
		}
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "list")
	public String list(EmpUser empUser, Model model) {
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		return "modules/sys/user/empUserList";
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<EmpUser> listData(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletRequest request, HttpServletResponse response) {
		
		User user = UserUtils.getUser();
		if(user.isAdmin()) {
			String loginAdmin = user.getLoginCode();
			logger.info("进行数据更新...判断是否是管理员....{}",loginAdmin);
			if(!org.springframework.util.StringUtils.isEmpty(loginAdmin)) {
				if (loginAdmin.indexOf("MANAGER") > -1) {
						Employee employee = empUser.getEmployee();
						String createBy = loginAdmin.substring(0,loginAdmin.indexOf("_MANAGER"));
						String[] values = null;
						if(!org.springframework.util.StringUtils.isEmpty(EduTwoOrganizationValues.map.get(loginAdmin))) {
							EduTwoOrganization eduTwoOrganization = new EduTwoOrganization();
							eduTwoOrganization.getSqlMap().getWhere()
							.andBracket("create_by", QueryType.EQ, createBy,2).or("create_by", QueryType.EQ, "system",3).endBracket()
							.and("dict_label", QueryType.EQ, EduTwoOrganizationValues.map.get(loginAdmin));
							List<EduTwoOrganization> eduTwoOrganizations = eduTwoOrganizationService.findList(eduTwoOrganization);
							
							List<String> ll = new ArrayList<String>();
							for(EduTwoOrganization eo: eduTwoOrganizations) {
								ll.add(eo.getDictCode());
							}
							values = ll.toArray(new String[ll.size()]);
							if(CollectionUtils.isEmpty(ll)||ll.size()==0) {
								values = new String[] {"1"};
							}
							
							logger.info("AND->OR...START");
							QueryWhere QueryWhere = employee.getSqlMap().getWhere().and("two_organization_code",  QueryType.IN, values);
							logger.info("AND->OR...END--->" + QueryWhere.toSql());
							
							empUser.setEmployee(employee);
						}
						
						employee.setCreateBy(createBy);
						logger.info("是否进入变更状态...");
				}
				
				if (loginAdmin.indexOf("SUPER")>-1) {
					Employee ee = employeeService.get(user.getUserCode());
					String users = ee.getRemarks();
					if (!org.springframework.util.StringUtils.isEmpty(users) && users.indexOf("_ADMIN") > -1) {
						String[] codes = users.split(",");
						empUser.getSqlMap().getWhere().and("create_by", QueryType.IN, codes); 
					}
				}
			}
		}
		empUser.getEmployee().getOffice().setIsQueryChildren(true);
		empUser.getEmployee().getCompany().setIsQueryChildren(true);
		if (!(isAll != null && isAll)){
			empUserService.addDataScopeFilter(empUser, ctrlPermi);
		}
		
		empUser.setPage(new Page<>(request, response));
		
		Page<EmpUser> page = empUserService.findPage(empUser);
		return page;
	}

	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "form")
	public String form(EmpUser empUser, String op, Model model) {
		
		Employee employee = empUser.getEmployee();
		
		// 设置默认的部门
		if (StringUtils.isBlank(employee.getCompany().getCompanyCode())) {
			employee.setCompany(EmpUtils.getCompany());
		}
		
		// 设置默认的公司
		if (StringUtils.isBlank(employee.getOffice().getOfficeCode())) {
			employee.setOffice(EmpUtils.getOffice());
		}
		
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		
		// 获取当前用户所拥有的岗位
		if (StringUtils.isNotBlank(employee.getEmpCode())){
			List<EmployeePost> ll = employeeService.findEmployeePostList(employee);
			if(!CollectionUtils.isEmpty(ll)) {
				employee.setEmployeePostList(ll);
				employee.setPostCode(ll.get(0).getPostCode());
			}
		}
		
		// 获取当前编辑用户的角色和权限
		if (StringUtils.inString(op, Global.OP_AUTH)) {
			
			// 获取当前用户所拥有的角色
			Role role = new Role();
			role.setUserCode(empUser.getUserCode());
			model.addAttribute("roleList", roleService.findListByUserCode(role));

		}
		// 操作类型：add: 全部； edit: 编辑； auth: 授权
		model.addAttribute("op", op);
		model.addAttribute("empUser", empUser);
		return "modules/sys/user/empUserForm";
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "info")
	public String info(String op, Model model) {
		User user = UserUtils.getUser();
		EmpUser empUser = empUserService.get(user.getUserCode());
		if(org.springframework.util.StringUtils.isEmpty(empUser)) {
			empUser = new EmpUser();
			form(empUser,Global.OP_ADD, model);
		}
		return form(empUser,Global.OP_EDIT, model);
	}
	
	@RequestMapping(value = "teacher")
	public String teacher(String op,HttpServletRequest request,HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		EmpUser empUser = empUserService.get(user.getUserCode());
		if(org.springframework.util.StringUtils.isEmpty(empUser)) {
			empUser = new EmpUser();
			detail(empUser,Global.OP_ADD,request,response, model);
		}
		return detail(empUser,Global.OP_EDIT,request,response, model);
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "detail")
	public String detail(EmpUser empUser, String op,HttpServletRequest request,HttpServletResponse response, Model model) {
		
		Employee employee = empUser.getEmployee();
		
		// 设置默认的部门
		if (StringUtils.isBlank(employee.getCompany().getCompanyCode())) {
			employee.setCompany(EmpUtils.getCompany());
		}
		
		// 设置默认的公司
		if (StringUtils.isBlank(employee.getOffice().getOfficeCode())) {
			employee.setOffice(EmpUtils.getOffice());
		}
		
		// 获取岗位列表
		Post post = new Post();
		model.addAttribute("postList", postService.findList(post));
		
		// 获取当前用户所拥有的岗位
		if (StringUtils.isNotBlank(employee.getEmpCode())){
			List<EmployeePost> ll = employeeService.findEmployeePostList(employee);
			if(!CollectionUtils.isEmpty(ll)) {
				employee.setEmployeePostList(ll);
				employee.setPostCode(ll.get(0).getPostCode());
			}
		}
		
		// 获取当前编辑用户的角色和权限
		if (StringUtils.inString(op, Global.OP_AUTH)) {
			
			// 获取当前用户所拥有的角色
			Role role = new Role();
			role.setUserCode(empUser.getUserCode());
			model.addAttribute("roleList", roleService.findListByUserCode(role));

		}
		
		employee.setCompany(companyService.get(employee.getCompany()));
		employee.setOffice(officeService.get(employee.getOffice()));
		empUser.setEmployee(employee);
		// 操作类型：add: 全部； edit: 编辑； auth: 授权
		String action = request.getParameter("action");
		model.addAttribute("action", action);
		model.addAttribute("op", op);
		model.addAttribute("empUser", empUser);
		return "modules/sys/user/empUserDetail";
	}
	
	@RequiresPermissions(value={"sys:empUser:edit","sys:empUser:authRole"}, logical=Logical.OR)
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated EmpUser empUser, String oldLoginCode, String op, HttpServletRequest request) {
		try {
		User oldUser = userService.get(empUser.getUserCode());
		Employee employee = empUser.getEmployee();
		if(!org.springframework.util.StringUtils.isEmpty(employee)&&!org.springframework.util.StringUtils.isEmpty(employee.getCompany())) {
			Company company = employee.getCompany();
			if (!org.springframework.util.StringUtils.isEmpty(company.getId()) && company.getId().equals("99999999") && !company.getCompanyName().equals("其他")) {
				String id = IdGenerate.nextId();
				Company entity = new Company();
				entity.setParent(companyService.get("99999999"));
				entity.setTreeLeaf("1");
				entity.setTreeLevel(0);
				entity.setTreeSort(30);
				entity.setTreeSorts("30,");
				entity.setViewCode(id);
				entity.setId(id);
				entity.setCompanyCode(id);
				entity.setCompanyName(company.getCompanyName());
				entity.setFullName(company.getCompanyName());
				entity.setStatus("0");
				entity.setIsNewRecord(true);
				companyService.save(entity);
				company = entity;
			}
		}
	
		
		if(!org.springframework.util.StringUtils.isEmpty(empUser.getSex())&&empUser.getSex().length()>1) {
			empUser.setSex(empUser.getSex().substring(0,1));
		}
		
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!Global.TRUE.equals(userService.checkLoginCode(oldLoginCode, empUser.getLoginCode()/*, null*/))) {
			return renderResult(Global.FALSE, text("保存用户失败，登录账号''{0}''已存在", empUser.getLoginCode()));
		}
		if (StringUtils.inString(op, Global.OP_ADD, Global.OP_EDIT)
				&& UserUtils.getSubject().isPermitted("sys:empUser:edit")){
			
			
			Employee oldEmployee = employeeService.get(employee);
			
			
			BeanChangeUtil<Employee> beanChangeUtil = new BeanChangeUtil<Employee>();
			String msg = "";
			EmployeePost ep = new EmployeePost();
			if(!org.springframework.util.StringUtils.isEmpty(oldEmployee)) {
				msg = beanChangeUtil.contrastObj(oldEmployee, employee);
				ep.setEmpCode(oldEmployee.getEmpCode());
			}
		
			
			Log.info("内容修改~:{}",msg);
			
			if(!org.springframework.util.StringUtils.isEmpty(msg)) {
				if(org.springframework.util.StringUtils.isEmpty(oldEmployee.getOp())) {
					employee.setOp(msg);
				}else {
					employee.setOp(oldEmployee.getOp() + " " + msg);
				}	
			}
			
			List<EmployeePost> oldEmployeePosts = postService.findListEmployeePost(ep);
			List<EmployeePost> employeePosts = employee.getEmployeePostList();
			if (!CollectionUtils.isEmpty(oldEmployeePosts) ) {
				EmployeePost oldEmployeePost = oldEmployeePosts.get(0);
				oldEmployeePost.setEmpCode(null);
				EmployeePost employeePost = employeePosts.get(0);
				BeanChangeUtil<EmployeePost> bc = new BeanChangeUtil<EmployeePost>();
				msg = bc.contrastObj(oldEmployeePost, employeePost);
				if(!org.springframework.util.StringUtils.isEmpty(msg)) {
					employee.setOp(employee.getOp() + " " + msg);
				}
			}

			
			if(!org.springframework.util.StringUtils.isEmpty(oldUser)) {
				String oldUsername = oldUser.getUserName();
				String oldSex = oldUser.getSex();
				String oldMobile = oldUser.getMobile();
				Extend oldExt = oldUser.getExtend();
				out:if(!org.springframework.util.StringUtils.isEmpty(oldExt)) {
					String oldExt1 = oldExt.getExtendS1();
					String oldExt2 = oldExt.getExtendS2();
					String oldExt3 = oldExt.getExtendS3();
					
					String username = empUser.getUserName();
					String sex = empUser.getSex();
					String mobile = empUser.getMobile();
					Extend ext = empUser.getExtend();
					if(org.springframework.util.StringUtils.isEmpty(ext)) {
						break out;
					}
					String ext1 = ext.getExtendS1();
					String ext2 = ext.getExtendS2();
					String ext3 = ext.getExtendS3();
					StringBuilder sb = new StringBuilder();
					if(!org.springframework.util.StringUtils.isEmpty(username)&&!oldUsername.equals(username)) {
						sb.append("姓名 ："  + oldUsername+ "\t => " + username +"\n <br>");
					}
					if(!org.springframework.util.StringUtils.isEmpty(sex)&&!oldSex.equals(sex)) {
						sb.append("性别 ："  + DictUtils.getDictLabel("sys_user_sex", oldSex, "")+ "\t => " + DictUtils.getDictLabel("sys_user_sex", sex, "")+"\n <br>");
					}
					if(!org.springframework.util.StringUtils.isEmpty(oldMobile)&&!oldMobile.equals(mobile)) {
						sb.append("手机号 ："  + oldUsername + "修改后=>" + mobile+"\n <br>");
					}
					
					if(!oldExt1.equals(ext1)) {
						sb.append("国籍 ："  + DictUtils.getDictLabel("js_sys_country", oldExt1, "") + "\t => " + DictUtils.getDictLabel("js_sys_country", ext1, "")+"\n <br>");
					}
					if(!oldExt2.equals(ext2)) {
						sb.append("民族 ："  + DictUtils.getDictLabel("nation", oldExt2, "") + "\t => " + DictUtils.getDictLabel("nation", ext2, "")+"\n <br>");
					}
					if(!oldExt3.equals(ext3)) {
						sb.append("政治面貌 ："  + DictUtils.getDictLabel("political", oldExt3, "") + "\t => " + DictUtils.getDictLabel("political", ext3, "")+"\n <br>");
					}
					if(!org.springframework.util.StringUtils.isEmpty(sb.toString())) {
						employee.setOp(employee.getOp() + " " + sb.toString());
					}
				}
				
			}
			
			empUser.getEmployee().setEmployeePostList(employeePosts);
			empUserService.save(empUser);
			
			
			
			/*
			if(!org.springframework.util.StringUtils.isEmpty(oldEmployee)&&!org.springframework.util.StringUtils.isEmpty(employee)) {
				
				List<EmployeePost>  employeePosts = employee.getEmployeePostList();
				if (!CollectionUtils.isEmpty(oldEmployeePosts) && !CollectionUtils.isEmpty(employeePosts)) {
					EmployeePost oldEmployeePost = oldEmployeePosts.get(0);
					EmployeePost employeePost = employeePosts.get(0);
					String oldPostCode = oldEmployeePost.getPostCode();
					String postCode = employeePost.getPostCode();
					if(!oldPostCode.equals(postCode)) {
						Post oldPost = postService.get(oldPostCode);
						Post post = postService.get(postCode);
						if(!org.springframework.util.StringUtils.isEmpty(postCode)&&!org.springframework.util.StringUtils.isEmpty(postCode)) {
							Op op1 = new Op();
							op1.setTitle("岗位操作");
							op1.setBefore(oldPost.getPostName());
							op1.setAfter(post.getPostName());
							list.add(op1);
						}
						
					}
				}
			}*/
		}
		if (StringUtils.inString(op, Global.OP_ADD, Global.OP_AUTH)
				&& UserUtils.getSubject().isPermitted("sys:empUser:authRole")){
			//userService.saveAuth(empUser);
		}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return renderResult(Global.TRUE, text("保存用户''{0}''成功", empUser.getUserName()));
	}
	
	

	/**
	 * 导出用户数据
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportData_history")
	public void exportData_history(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		empUser.getEmployee().getOffice().setIsQueryChildren(true);
		empUser.getEmployee().getCompany().setIsQueryChildren(true);
		if (!(isAll != null && isAll)){
			empUserService.addDataScopeFilter(empUser, ctrlPermi);
		}
		List<EmpUser> list = empUserService.findList(empUser);
		String fileName = "教师数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("教师数据", EmpUser.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportData")
	public void exportData(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		
		try {
			response.setHeader("content-Disposition","attachment;filename="
					+ URLEncoder.encode("报表.xlsx","utf-8"));
			XSSFWorkbook wb = empUserService.exportData(empUser, isAll, ctrlPermi);
			OutputStream out = response.getOutputStream();
			wb.write(out);
			wb.close();
			out.flush();
			out.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "averageAssign")
	public void averageAssign(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		
		try {
			empUserService.averageAssign(empUser, isAll, ctrlPermi);
		}catch(Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportAll")
	public void exportAll(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletResponse response) {

		try {
			File path = new File(ResourceUtils.getURL("classpath:").getPath());
			if (!path.exists()) {
				path = new File("");
			}
			File upload = new File(path.getAbsolutePath(), "static/upload/");
			if (!upload.exists()) {
				upload.mkdirs();
			}
			File file = new File(upload, DateUtils.getDate() + ".xlsx");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(file);
			XSSFWorkbook wb = empUserService.exportData(empUser, isAll, ctrlPermi);
			wb.write(out);
			wb.close();
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * 导出用户数据
	 * @throws IOException 
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportAllData")
	@ResponseBody
	public String exportAllData(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletRequest request,HttpServletResponse response) throws IOException {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		
		File file = new File("/home/git/jeesite4/upload");
		if(!file.exists()) {
			file.mkdirs();
		}
		systemService.exportAll(empUser, isAll, ctrlPermi, file, fileName);
		return fileName;
	}
	
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "listExport")
	public String listExport(EmpUser empUser, Boolean isAll, String ctrlPermi, HttpServletRequest request,HttpServletResponse response,Model model) throws IOException {
		
		
		File file = new File("/home/git/jeesite4/upload");
		if(file.exists()) {
			String[] chengjis = file.list();
			List<String> lcs = new ArrayList<String>();
			for(String cjs : chengjis) {
				lcs.add(cjs);
			}
			model.addAttribute("chengjis", lcs);
		}
		return "modules/sys/user/listExport";
	}
	

	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		EmpUser empUser = new EmpUser();
		User user = UserUtils.getUser();
		if (User.USER_TYPE_EMPLOYEE.equals(user.getUserType())){
			empUser = empUserService.get(user.getUserCode());
		}else{
			BeanUtils.copyProperties(user, empUser);
		}
		List<EmpUser> list = ListUtils.newArrayList(empUser);
		String fileName = "教师数据模板.xlsx";
		try(ExcelExport ee = new ExcelExport("教师数据", EmpUser.class, Type.IMPORT)){
			ee.setDataList(list).write(response, fileName);
		}
	}

	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("sys:empUser:edit")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			String message = empUserService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}
	
	/**
	 * 停用用户
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("sys:empUser:updateStatus")
	@ResponseBody
	@RequestMapping(value = "disable")
	public String disable(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (empUser.getCurrentUser().getUserCode().equals(empUser.getUserCode())) {
			return renderResult(Global.FALSE, text("停用用户失败，不允许停用当前用户"));
		}
		empUser.setStatus(User.STATUS_DISABLE);
		userService.updateStatus(empUser);
		return renderResult(Global.TRUE, text("停用用户''{0}''成功", empUser.getUserName()));
	}
	
	/**
	 * 启用用户
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("sys:empUser:updateStatus")
	@ResponseBody
	@RequestMapping(value = "enable")
	public String enable(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		empUser.setStatus(User.STATUS_NORMAL);
		userService.updateStatus(empUser);
		return renderResult(Global.TRUE, text("启用用户''{0}''成功", empUser.getUserName()));
	}
	
	/**
	 * 密码重置
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("sys:empUser:resetpwd")
	@RequestMapping(value = "resetpwd")
	@ResponseBody
	public String resetpwd(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		userService.updatePassword(empUser.getUserCode(), null);
		return renderResult(Global.TRUE, text("重置用户''{0}''密码成功", empUser.getUserName()));
	}

	/**
	 * 删除用户
	 * @param empUser
	 * @return
	 */
	@RequiresPermissions("sys:empUser:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (empUser.getCurrentUser().getUserCode().equals(empUser.getUserCode())) {
			return renderResult(Global.FALSE, text("删除用户失败，不允许删除当前用户"));
		}
		empUserService.delete(empUser);
		return renderResult(Global.TRUE, text("删除用户'{0}'成功", empUser.getUserName()));
	}
	
	@RequiresPermissions("sys:empUser:remove")
	@RequestMapping(value = "remove")
	@ResponseBody
	public String removce(EmpUser empUser) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (empUser.getCurrentUser().getUserCode().equals(empUser.getUserCode())) {
			return renderResult(Global.FALSE, text("删除用户失败，不允许删除当前用户"));
		}
		systemService.remove(empUser.getUserCode());
		return renderResult(Global.TRUE, text("删除用户'{0}'成功", empUser.getUserName()));
	}
	
	/** 
	 * 用户授权数据权限
	 */
	@RequiresPermissions("sys:empUser:authDataScope")
	@RequestMapping(value = "formAuthDataScope")
	public String formAuthDataScope(EmpUser empUser, Model model, HttpServletRequest request) {
		UserDataScope userDataScope = new UserDataScope();
		userDataScope.setUserCode(empUser.getUserCode());
		userDataScope.setCtrlPermi(UserDataScope.CTRL_PERMI_HAVE);
		List<UserDataScope> userDataScopeList = userService.findDataScopeList(userDataScope);
		model.addAttribute("userDataScopeList", userDataScopeList);
		model.addAttribute("empUser", empUser);
		return "modules/sys/user/empUserFormAuthDataScope";
	}
	
	/** 
	 * 保存用户授权数据权限
	 */
	@RequiresPermissions("sys:empUser:authDataScope")
	@RequestMapping(value = "saveAuthDataScope")
	@ResponseBody
	public String saveAuthDataScope(EmpUser empUser, HttpServletRequest request) {
		if (User.isSuperAdmin(empUser.getUserCode())) {
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		if (!EmpUser.USER_TYPE_EMPLOYEE.equals(empUser.getUserType())){
			return renderResult(Global.FALSE, "非法操作，不能够操作此用户！");
		}
		empUser.setMgrType(User.MGR_TYPE_NOT_ADMIN);
		userService.saveAuthDataScope(empUser);
		return renderResult(Global.TRUE, text("用户分配数据权限成功"));
	}

	/**
	 * 根据机构查询用户树格式
	 * @param idPrefix id前缀，默认 u_
	 * @param pId 父级编码，默认 0
	 * @param officeCode 机构Code
	 * @param companyCode 公司Code
	 * @param postCode 岗位Code
	 * @param roleCode 角色Code
	 * @param isAll 是否显示所有用户（true：不进行权限过滤）
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String idPrefix, String pId,
			String officeCode, String companyCode, String postCode, String roleCode, 
			Boolean isAll, String isShowCode, String ctrlPermi) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		EmpUser empUser = new EmpUser();
		Employee employee = empUser.getEmployee();
		employee.getOffice().setOfficeCode(officeCode);
		employee.getOffice().setIsQueryChildren(false);
		employee.getCompany().setCompanyCode(companyCode);
		employee.getCompany().setIsQueryChildren(false);
		employee.setPostCode(postCode);
		empUser.setRoleCode(roleCode);
		empUser.setStatus(User.STATUS_NORMAL);
		empUser.setUserType(User.USER_TYPE_EMPLOYEE);
		if (!(isAll != null && isAll)) {
			empUserService.addDataScopeFilter(empUser, ctrlPermi);
		}
		List<EmpUser> list = empUserService.findList(empUser);
		for (int i = 0; i < list.size(); i++) {
			EmpUser e = list.get(i);
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", StringUtils.defaultIfBlank(idPrefix, "u_") + e.getId());
			map.put("pId", StringUtils.defaultIfBlank(pId, "0"));
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getLoginCode(), e.getUserName()));
			mapList.add(map);
		}
		return mapList;
	}
	@RequiresPermissions("user")
	@RequestMapping(value = "state")
	public String state(EmpUser empUser, Model model, HttpServletRequest request) {
		return "modules/sys/user/state";
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "stateListData")
	@ResponseBody
	public List<UserState> stateListData() {
		User user = UserUtils.getUser();
		String officeCode = null;
		if (!user.getLoginCode().equals("system")) {
			Employee employee = employeeService.get(user.getUserCode());
			if(!org.springframework.util.StringUtils.isEmpty(employee)) {
				Office office = employee.getOffice();
				if(!org.springframework.util.StringUtils.isEmpty(office)) {
					officeCode = office.getOfficeCode();
				}
				
			}
		}
		
		return employeeService.totalUserState(officeCode);
	}
	
	/**
	 * 选择员工对话框
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "empUserSelect")
	public String empUserSelect(EmpUser empUser, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (JsonMapper.fromJson(selectDataJson, Map.class) != null){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("empUser", empUser);
		return "modules/sys/user/empUserSelect";
	}
	
}
